/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.evolve.webbot.portal;
import  java.io.File;
import  java.io.FileOutputStream;
import  java.io.FileInputStream;
import  java.io.FileWriter;
import  java.io.BufferedWriter;
import  java.io.InputStream;
import  java.io.OutputStream;
import  java.io.IOException;
import  java.util.Date;
import  java.util.ArrayList;
import  java.text.SimpleDateFormat;
import  java.util.Properties;
import  org.apache.log4j.Logger;
import  com.gargoylesoftware.htmlunit.WebClient;
import  com.gargoylesoftware.htmlunit.html.HtmlForm;
import  com.gargoylesoftware.htmlunit.html.HtmlPage;
import  com.gargoylesoftware.htmlunit.html.HtmlSubmitInput;
import  com.gargoylesoftware.htmlunit.html.HtmlInput;
import  com.gargoylesoftware.htmlunit.html.HtmlTextInput;
import  com.gargoylesoftware.htmlunit.html.HtmlPasswordInput;
import  com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController;
import java.awt.Font;
import  javax.swing.JTextArea;
import  java.awt.color.*;
import  java.awt.font.*;
import  com.evolve.webbot.beans.WebBotBeans;
import  com.evolve.webbot.bean.Sanbrns;
import  com.evolve.webbot.file.TxtSanborns;
import  com.evolve.webbot.file.CommonErrorFile;

/**
 *
 * @author DarthAE
 */
public class Sanborns
{
   static Logger log = Logger.getLogger( Sanborns.class );
   private String path;
   private JTextArea jtextArea;
   public static String WB_MAIN_DIR="evolve-webbot";
   public static String SANBORNS_MAIN_DIR="sanborns-webbot";
   public static String SANBORNS_PROP_DIR="sanborns-properties";
   public static String SANBORNS_PROP_ARC="SanbornsPortal.properties";
   public static String SANBORNS_FILE_DIR="sanborns-files";
   public static String SANBORNS_ARC_EXT =".txt";   
   
   public static String SANBORNS_ERROR_FILE = "sanborns-error-";
   
   private SimpleDateFormat sdf = new SimpleDateFormat("yyyymmdd");
   private SimpleDateFormat shf = new SimpleDateFormat("HHmmss");
   
   private SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MM/yyyy");

   public Sanborns(){}
   
   public Sanborns(String path)
   {
       this.path = path;
   }

   public Sanborns(String path,JTextArea jtextArea)
   {
       this.path      = path;
       this.jtextArea = jtextArea;
   }

   public WebClient creaWebClient()
   {
       WebClient webClient = null;

       webClient = new WebClient();
       webClient.setJavaScriptEnabled(true);
       webClient.setThrowExceptionOnScriptError(false);
       webClient.setAjaxController(new NicelyResynchronizingAjaxController());

       return webClient;
   }

   public boolean accesoPortal(WebClient webClient,
                               WebBotBeans webBotBean,int opt)
   {
      this.jtextArea.append("\nrecuperando archivo sanborns");
      
      boolean creaArchivo = false;
      Properties properties = new Properties();

      try{
           System.out.println(this.path+File.separator+WB_MAIN_DIR+
                                        File.separator+SANBORNS_MAIN_DIR+
                                        File.separator+SANBORNS_PROP_DIR+
                                        File.separator+SANBORNS_PROP_ARC);
           
           FileInputStream fis = new FileInputStream(this.path+File.separator+WB_MAIN_DIR+
                                                               File.separator+SANBORNS_MAIN_DIR+
                                                               File.separator+SANBORNS_PROP_DIR+
                                                               File.separator+SANBORNS_PROP_ARC);
           properties.load(fis);

           try{
                HtmlPage          pg1 = (HtmlPage)webClient.getPage(properties.getProperty("Sanborns.UrlLogin"));
                HtmlForm          fm1 = (HtmlForm)pg1.getFormByName(properties.getProperty("Sanborns.FormNameLogin"));
                HtmlTextInput     ti1 = (HtmlTextInput)fm1.getInputByName(properties.getProperty("Sanborns.UsrFormName"));
                HtmlPasswordInput pw1 = (HtmlPasswordInput)fm1.getInputByName(properties.getProperty("Sanborns.PwdFormName"));

                ti1.setValueAttribute(properties.getProperty("Portal.user"));
                pw1.setValueAttribute(properties.getProperty("Portal.passwd"));

                HtmlSubmitInput si1 =(HtmlSubmitInput)fm1.getInputByName(properties.getProperty("Sanborns.SmtFormName"));
                HtmlPage        pg2  = (HtmlPage)si1.click();

                if(pg2!=null)
                {
                  HtmlPage pg3 = (HtmlPage)webClient.getPage(properties.getProperty("Sanborns.UrlCyV"));

                  if(pg3!=null)
                  {
                     HtmlForm      fm2  = (HtmlForm)pg3.getFormByName(properties.getProperty("Sanborns.FormNameReporte"));
                     HtmlTextInput td1 = (HtmlTextInput)fm2.getInputByName(properties.getProperty("Sanborns.Dt1FormName"));
                     HtmlTextInput td2 = (HtmlTextInput)fm2.getInputByName(properties.getProperty("Sanborns.Dt2FormName"));

                     SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MM/yyyy");
                     
                     td1.setValueAttribute(sdf1.format(webBotBean.getSanbornsFBusquedaIni()));
                     td2.setValueAttribute(sdf1.format(webBotBean.getSanbornsFBusquedaFin()));

                     HtmlInput im1  =(HtmlInput)fm2.getInputByName(properties.getProperty("Sanborns.ImpFormName"));
                     HtmlPage  pg4  =(HtmlPage)im1.click();

                     webClient.waitForBackgroundJavaScriptStartingBefore(10000);
                     synchronized (pg4) {pg4.wait(500);}

                     try{
                          InputStream  is  = pg4.getWebResponse().getContentAsStream();

                          Date fileDate = new Date();
                          
                          fileDate.setTime(webBotBean.getSanbornsFBusquedaIni().getTime());
                          SimpleDateFormat dateFotmat = new SimpleDateFormat("ddMMyyyy");
                          SimpleDateFormat timeFotmat = new SimpleDateFormat("HHmmss");

                           OutputStream out = new FileOutputStream(new File(this.path+File.separator+WB_MAIN_DIR+
                                                                                  File.separator+SANBORNS_MAIN_DIR+
                                                                                  File.separator+SANBORNS_FILE_DIR+
                                                                                  File.separator+properties.getProperty("Sanborns.ArchivoPortal")+"-"+
                                                                                  dateFotmat.format(fileDate)+"-"+timeFotmat.format(fileDate)+SANBORNS_ARC_EXT));

                          int read=0;
                          byte[] bytes = new byte[1024];

                          while((read = is.read(bytes))!= -1)
                          {out.write(bytes, 0, read);}

                          is.close();
                          out.flush();
                          out.close();
                          
                          this.jtextArea.append("\narchivo generado");
                          creaArchivo=true;

                        }catch(IOException ioe){ this.jtextArea.append("\nno se ha podido generar el archivo de datos"); }
                  }
                }

              }catch(Exception e){this.jtextArea.append("\nerror al ingresar al portal");
           }

         }catch(IOException ioe){System.out.println(ioe);}

      return creaArchivo;
   }   
   
   public boolean accesoPortal(WebClient webClient,
                               String strDate1,String strDate2)
   {
      boolean creaArchivo   = false;
      Properties properties = new Properties();

      try{
           System.out.println(this.path+File.separator+WB_MAIN_DIR+
                                        File.separator+SANBORNS_MAIN_DIR+
                                        File.separator+SANBORNS_PROP_DIR+
                                        File.separator+SANBORNS_PROP_ARC);
           
           FileInputStream fis = new FileInputStream(this.path+File.separator+WB_MAIN_DIR+
                                                               File.separator+SANBORNS_MAIN_DIR+
                                                               File.separator+SANBORNS_PROP_DIR+
                                                               File.separator+SANBORNS_PROP_ARC);
           properties.load(fis);

           try{
                HtmlPage          pg1 = (HtmlPage)webClient.getPage(properties.getProperty("Sanborns.UrlLogin"));
                HtmlForm          fm1 = (HtmlForm)pg1.getFormByName(properties.getProperty("Sanborns.FormNameLogin"));
                HtmlTextInput     ti1 = (HtmlTextInput)fm1.getInputByName(properties.getProperty("Sanborns.UsrFormName"));
                HtmlPasswordInput pw1 = (HtmlPasswordInput)fm1.getInputByName(properties.getProperty("Sanborns.PwdFormName"));

                ti1.setValueAttribute(properties.getProperty("Sanborns.UsrPortal"));
                pw1.setValueAttribute(properties.getProperty("Sanborns.PwdPortal"));

                HtmlSubmitInput si1 =(HtmlSubmitInput)fm1.getInputByName(properties.getProperty("Sanborns.SmtFormName"));
                HtmlPage        pg2  = (HtmlPage)si1.click();

                if(pg2!=null)
                {
                  HtmlPage pg3 = (HtmlPage)webClient.getPage(properties.getProperty("Sanborns.UrlCyV"));

                  if(pg3!=null)
                  {
                     HtmlForm      fm2  = (HtmlForm)pg3.getFormByName(properties.getProperty("Sanborns.FormNameReporte"));
                     HtmlTextInput td1 = (HtmlTextInput)fm2.getInputByName(properties.getProperty("Sanborns.Dt1FormName"));
                     HtmlTextInput td2 = (HtmlTextInput)fm2.getInputByName(properties.getProperty("Sanborns.Dt2FormName"));

                     System.out.println("\nfecha inicio consulta:"+strDate1);
                     System.out.println("\nfecha fin consulta:"+strDate2);
                     
                     td1.setValueAttribute(strDate1);
                     td2.setValueAttribute(strDate2);

                     HtmlInput im1  =(HtmlInput)fm2.getInputByName(properties.getProperty("Sanborns.ImpFormName"));
                     HtmlPage  pg4  =(HtmlPage)im1.click();

                     webClient.waitForBackgroundJavaScriptStartingBefore(10000);
                     synchronized (pg4) {pg4.wait(500);}

                     try{
                          InputStream  is  = pg4.getWebResponse().getContentAsStream();
                          System.out.println(pg4.asText());
                          Date fileDate    = new Date();
                          
                          SimpleDateFormat dateFotmat = new SimpleDateFormat("ddMMyyyy");
                          SimpleDateFormat timeFotmat = new SimpleDateFormat("HHmmss");

                          OutputStream out = new FileOutputStream(new File(this.path+File.separator+WB_MAIN_DIR+
                                                                                  File.separator+SANBORNS_MAIN_DIR+
                                                                                  File.separator+SANBORNS_FILE_DIR+
                                                                                  File.separator+properties.getProperty("Sanborns.ArchivoPortal")+"-"+
                                                                                  dateFotmat.format(fileDate)+"-"+timeFotmat.format(fileDate)+".html"));

                          int read=0;
                          byte[] bytes = new byte[1024];

                          while((read = is.read(bytes))!= -1)
                          {out.write(bytes, 0, read);}

                          is.close();
                          out.flush();
                          out.close();
                          
                          System.out.println("\narchivo generado");
                          
                            BufferedWriter ou = new BufferedWriter(new FileWriter(this.path+File.separator+WB_MAIN_DIR+
                                                                                  File.separator+SANBORNS_MAIN_DIR+
                                                                                  File.separator+SANBORNS_FILE_DIR+
                                                                                  File.separator+properties.getProperty("Sanborns.ArchivoPortal")+"-"+
                                                                                  dateFotmat.format(fileDate)+"-"+timeFotmat.format(fileDate)+"-mensual"+SANBORNS_ARC_EXT));

                            ou.write(pg4.asText());
                 
                            ou.flush();
                            ou.close();
                          
                            creaArchivo=true;

                        }catch(IOException ioe){ System.out.println("\nno se ha podido generar el archivo de datos"); }
                  }
                }

              }catch(Exception e){System.out.println("\nerror al ingresar al portal");
           }

         }catch(IOException ioe){System.out.println(ioe);}

      return creaArchivo;
   }   

   /*------------------------------------------------------------------*/
     public boolean accesoPortal(WebClient webClient,
                                 WebBotBeans webBotBean)
   {
      int  indPortalEjec = 0; 
      Date thisDate = new Date();
      boolean creaArchivo   = false;
      Properties properties = new Properties();
      String     sanbornsFilePath = null;
      String errorFilePath    = "";
      
      CommonErrorFile   cef = new CommonErrorFile();
      
      try{       
          
          errorFilePath = this.path+File.separator+WB_MAIN_DIR+
                             File.separator+SANBORNS_MAIN_DIR+
                             File.separator+SANBORNS_FILE_DIR+
                             File.separator+SANBORNS_ERROR_FILE+
                             sdf.format(thisDate)+"-"+
                             shf.format(thisDate)+".txt";
           
           FileInputStream fis = new FileInputStream(this.path+File.separator+WB_MAIN_DIR+
                                                               File.separator+SANBORNS_MAIN_DIR+
                                                               File.separator+SANBORNS_PROP_DIR+
                                                               File.separator+SANBORNS_PROP_ARC);
           properties.load(fis);
           
           indPortalEjec = Integer.parseInt(properties.getProperty("Portal.ejecuta"));
           
           if(indPortalEjec==1)
           {
              this.jtextArea.append("\n[+]recuperando archivo sanborns");
              
              log.info("[-]recuperando archivo de sanborns");
      
              try{                
                   HtmlPage          pg1 = (HtmlPage)webClient.getPage(properties.getProperty("Sanborns.UrlLogin"));
                   HtmlForm          fm1 = (HtmlForm)pg1.getFormByName(properties.getProperty("Sanborns.FormNameLogin"));
                   HtmlTextInput     ti1 = (HtmlTextInput)fm1.getInputByName(properties.getProperty("Sanborns.UsrFormName"));
                   HtmlPasswordInput pw1 = (HtmlPasswordInput)fm1.getInputByName(properties.getProperty("Sanborns.PwdFormName"));

                   ti1.setValueAttribute(properties.getProperty("Portal.user"));
                   pw1.setValueAttribute(properties.getProperty("Portal.passwd"));                

                   HtmlSubmitInput si1 =(HtmlSubmitInput)fm1.getInputByName(properties.getProperty("Sanborns.SmtFormName"));
                   HtmlPage        pg2  = (HtmlPage)si1.click();

                   if(pg2!=null)
                   {
                     HtmlPage pg3 = (HtmlPage)webClient.getPage(properties.getProperty("Sanborns.UrlCyV"));

                     if(pg3!=null)
                     {
                        HtmlForm      fm2  = (HtmlForm)pg3.getFormByName(properties.getProperty("Sanborns.FormNameReporte"));
                        HtmlTextInput td1 = (HtmlTextInput)fm2.getInputByName(properties.getProperty("Sanborns.Dt1FormName"));
                        HtmlTextInput td2 = (HtmlTextInput)fm2.getInputByName(properties.getProperty("Sanborns.Dt2FormName"));
                     
                        log.info("\nfecha inicio consulta:"+sdf1.format(webBotBean.getSanbornsFBusquedaIni()));
                        log.info("\nfecha fin consulta:"+sdf1.format(webBotBean.getSanbornsFBusquedaFin()));
                     
                        this.jtextArea.append("\nfecha inicio consulta:"+sdf1.format(webBotBean.getSanbornsFBusquedaIni()));
                        this.jtextArea.append("\nfecha fin consulta:"+sdf1.format(webBotBean.getSanbornsFBusquedaFin()));
                                          
                        td1.setValueAttribute(sdf1.format(webBotBean.getSanbornsFBusquedaIni()));
                        td2.setValueAttribute(sdf1.format(webBotBean.getSanbornsFBusquedaFin()));

                        HtmlInput im1  =(HtmlInput)fm2.getInputByName("Consultar");
                        HtmlPage  pg4  =(HtmlPage)im1.click();

                        webClient.waitForBackgroundJavaScriptStartingBefore(10000);
                         synchronized (pg4) {pg4.wait(500);}

                         try{
                              InputStream  is  = pg4.getWebResponse().getContentAsStream();
                          
                              SimpleDateFormat dateFotmat = new SimpleDateFormat("ddMMyyyy");
                              SimpleDateFormat timeFotmat = new SimpleDateFormat("HHmmss");                         
                          
                              sanbornsFilePath = this.path+File.separator+WB_MAIN_DIR+
                                                           File.separator+SANBORNS_MAIN_DIR+
                                                           File.separator+SANBORNS_FILE_DIR+
                                                           File.separator+properties.getProperty("Sanborns.ArchivoPortal")+"-"+
                                                           dateFotmat.format(webBotBean.getSanbornsFBusquedaIni())+"-"+
                                                           timeFotmat.format(webBotBean.getSanbornsFBusquedaIni())+
                                                           SANBORNS_ARC_EXT;
                          
                              BufferedWriter ou = new BufferedWriter(new FileWriter(sanbornsFilePath));

                              ou.write(pg4.asText());
                 
                              ou.flush();
                              ou.close();
                          
                              creaArchivo=true;
                              this.jtextArea.append("\narchivo generado");
                              this.jtextArea.append("\ngeneracion de archivo de datos para reporte");
                          
                              ArrayList<Sanbrns> sanbornsRecordList = new ArrayList<Sanbrns>();
                              TxtSanborns txtSanborns               = new TxtSanborns(sanbornsFilePath);
        
                              sanbornsRecordList = txtSanborns.readSanbornsTxtFile();
                              txtSanborns.writeSanbornsDataFile(sanbornsRecordList);

                              this.jtextArea.append("\narchivo de datos generado");
                              log.info("[+]archivo de datos generado");
                          
                            }catch(IOException ioe){ log.info("no se ha podido generar el archivo de datos"); 
                                                     this.jtextArea.append("\nno se ha podido generar el archivo de datos");
                                                     cef.writeCommonWebTxtFile(errorFilePath,"no se ha podido generar el archivo de datos");
                                                    }
                      }
                    }

                  }catch(Exception e){this.jtextArea.append("\nno se ha podido generar el archivo de datos");
                                      cef.writeCommonWebTxtFile(errorFilePath,"no se ha podido generar el archivo de datos");
                                     }
           }
           else
           if(indPortalEjec==0)
           {
                this.jtextArea.append("[-]Portal Coppel Desactivado");
                log.info("[-]Portal Coppel Desactivado");               
           }
               
         }catch(IOException ioe){log.error("[-]error de navegacion portal sanborns ",ioe);
                                 cef.writeCommonWebTxtFile(errorFilePath,"error al ingresar al portal sanborns");
                                 }

      return creaArchivo;
   }
   /*------------------------------------------------------------------*/
   
   public void terminaWebClient(WebClient webClient)
   {
       if(webClient!=null)
       {webClient.closeAllWindows();}
   }
}
